import { getBaseUrl } from '@/services/urlconst';
import { ManageCommonAPI } from '@/pages/type';
import { useRequest } from 'umi';
import { commonManageSearchParams, getLevelZero, getLoadMapList, getTenantID, getUserID, requestFunComponFiex } from '@/utils';
import { ILoadMapTypeAll, ISearchTranslateAll } from '@/common';
import { useEffect, useMemo } from 'react';
import { getMaterialSearchList } from '../mconfig/UpdateSearchColumns';
import { AssetMaterialManage } from '../mconfig';
import { getCompanyTreeNodeListSev } from '@/services/BaseLayout';

const baseUrl = getBaseUrl();
// const baseUrl = '/wenchuang';

function findTreeNodeByIdInArray(treeArray, id) {
  // 遍历数组中的每个元素（每个元素都应该是一个树节点）
  for (let tree of treeArray) {
    // 递归地在当前树节点中查找ID
    let foundNode = findTreeNodeById(tree, id);
    if (foundNode) {
      // 如果找到了，就返回它
      return foundNode;
    }
  }
  // 如果没有在任何树节点中找到，就返回null
  return null;
}
// 辅助函数，用于在单个树节点（或其子节点）中查找ID
function findTreeNodeById(tree, id) {
  if (!tree) return null; // 基本终止条件
  if (tree.id === id) return tree; // 如果当前节点匹配，则返回它
  // 递归地在子节点中查找
  for (let child of tree.children || []) {
    let found = findTreeNodeById(child, id);
    if (found) return found; // 如果在子节点中找到，则返回它
  }
  return null; // 如果没有找到，则返回null
}

/**
 * 资产列表
 * @param curRes
 */
const materialTableService = (curRes: Record<string, any>, originalStoreID, isTransferType) => {
  // 获取最大组织结构树
  const { companyTreeNodeListRun, companyTreeNodeListLoading, companyTreeNodeList } = getCompanyTreeNodeListSev();

  /**  需要获取的资产类别数据字典 */
  const loadMdicIds: string[] = [`${getTenantID()}${ILoadMapTypeAll.MATERIAL_TYPE}`];

  /** 获取数据字典loadMdicMap */
  const loadMdicMapObj: Record<string, any> = getLoadMapList(loadMdicIds);

  /** 获取权限参数 */
  const queryTypeObj: Record<string, any> = AssetMaterialManage(curRes);

  /** 获取列表数据  */
  const { loading, run, refresh, tableProps, data, params } = useRequest(
    async (opt: ManageCommonAPI.IGridRequestType) => {
      const requestBody: Record<string, any> = {
        ...queryTypeObj,
        current: 1,
        pageSize: 10,
        sort: 'createTime',
        order: 'desc',
        assetState: `${getTenantID()}${ILoadMapTypeAll.MATERIEL_STATUS}1001`, // 查询已入库的
        // 原仓库id
        createDepartmentID: originalStoreID,
        ...opt,
      };

      let { transferType, originalStoreDepartmentID } = isTransferType();

      const companyTreeNodeList = await companyTreeNodeListRun();

      const treeNode = findTreeNodeByIdInArray(companyTreeNodeList?.obj, originalStoreDepartmentID);

      if (transferType == '2' && treeNode) {
        requestBody.createCompanyID = treeNode?.pID;
      }

      const requestURL = `${baseUrl}/assetMaterial/list/${queryTypeObj?.params}`;
      return requestFunComponFiex('POST', requestURL, requestBody);
    },
    {
      manual: false, //页面初始请求为 true
      paginated: true,
      defaultPageSize: 10,
    },
  );

  /**  获取管理也数据  */
  const getManageData = (otherRequest: ManageCommonAPI.IGridRequestType | any) => {
    const request: ManageCommonAPI.IGridRequestType | any = {
      ...otherRequest,
    };
    run({ ...request });
  };

  /** 搜索表单 */
  const searchList: any = getMaterialSearchList(loadMdicMapObj);

  /** 页面列表 */
  const returnTableProps = useMemo(() => {
    return {
      data,
      pagination: tableProps?.pagination,
      params: params?.[0],
    };
  }, [data, tableProps]);

  return {
    getManageData,
    refreshManage: refresh,
    loading,
    searchList,
    dataList: data?.rows,
    loadMdicMapObj,
    ...returnTableProps,
  };
};

/**
 * 获取仓库树列表
 * @param getStorageCallback
 * @returns
 */
const getStorageTreeService = (getStorageCallback: (res: any) => void) => {
  const getStorage = useRequest(
    () => {
      let personUrl = `${baseUrl}/assetStore/tree`;
      return requestFunComponFiex('GET', personUrl, {});
    },
    {
      manual: true,
      onSuccess: (res) => {
        getStorageCallback(res);
      },
    },
  );
  return {
    getStorageRun: getStorage?.run,
    getStorageLoading: getStorage?.loading,
  };
};

export { materialTableService, getStorageTreeService };
